package com.example.sanguogameserver.controller;

import com.example.sanguogameserver.consts.SanGuoConst;
import com.example.sanguogameserver.enums.ChatTypeEnum;
import com.example.sanguogameserver.request.ChatSendMessageReq;
import com.example.sanguogameserver.response.GetMessageResp;
import com.example.sanguogameserver.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.locks.Lock;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2024-03-26
 */
@RestController
@RequestMapping("/api/chat")
@Slf4j
public class ChatController {

    @Autowired
    private RedisLockRegistry redisLockRegistry;

    @Autowired
    private ChatService chatService;

    /**
     * 给用户发送消息
     *
     * @param chatSendMessageReq
     */
    @PostMapping("/sendMessage")
    public void sendMessage(@RequestBody ChatSendMessageReq chatSendMessageReq) {
        Lock lock = null;
        if (chatSendMessageReq.getChatType() == ChatTypeEnum.privateChat)
            lock = redisLockRegistry.obtain(SanGuoConst.RedisLock.messagePlayerId + chatSendMessageReq.getPlayerId());
        else if (chatSendMessageReq.getChatType() == ChatTypeEnum.world) {
            lock = redisLockRegistry.obtain(SanGuoConst.RedisLock.messageWorldServerId + chatSendMessageReq.getServerId());
        }


        if (lock.tryLock()) {
            try {
                // 业务代码块
                chatService.sendMessage(chatSendMessageReq);
            } finally {
                //走到这里说明获取锁一定是成功的
                try {
                    lock.unlock();
                } catch (IllegalStateException e) {
                    //业务操作时间过长，会导致锁超时内系统释放，这里就会产生超时异常
                    log.error("释放时发现锁过期", e);
                }

            }
        } else {
            //走到这里说明获取锁一定是失败的的
            log.info("发送消息太快了,等下再试试吧!");
        }
    }

    @GetMapping("/getMessage")
    public GetMessageResp getMessage(String worldMessageId, Integer attackTaskId) {
        return chatService.getMessage(worldMessageId,attackTaskId);
    }
}
